<template>
	<div>
		<p>count: {{ count }}</p>
		<el-divider></el-divider>
		<el-button type="primary" @click="increment">新增</el-button>
		<el-button type="success" @click="decrement">减少</el-button>
		<el-divider></el-divider>
		<p>浏览器窗口宽度: {{ width }}</p>
		<p>浏览器窗口高度: {{ height }}</p>
		<el-divider></el-divider>
		<button @click="fetchData">请求数据</button>
		<div>{{ percentage }}%</div>
		<el-progress v-if="percentage != 100" type="circle" :percentage="percentage"></el-progress>
        <el-progress v-else type="circle" :percentage="100" status="success"></el-progress>
	</div>
</template>

<script setup lang="ts">
// 导入 hooks
import axios from "axios"
import { userCount } from "../../hooks/userCount"
import { usewinResize } from "../../hooks/useWinResize"
// 解构引入
const { count, increment, decrement } = userCount()
const { width, height } = usewinResize()
const percentage = ref(0)
let timeoutId: ReturnType<typeof setTimeout>

function updatePercentageSmoothly(newPercentage: number) {
	let currentPercentage = percentage.value
	const targetPercentage = newPercentage
	const incrementAmount = Math.sign(targetPercentage - currentPercentage)
	const interval = 50 // 每隔 50 毫秒更新一次

	const tick = () => {
		if (
			(currentPercentage < targetPercentage && incrementAmount > 0) ||
			(currentPercentage > targetPercentage && incrementAmount < 0)
		) {
			currentPercentage += incrementAmount
			percentage.value = currentPercentage
			timeoutId = setTimeout(tick, interval)
		} else {
			percentage.value = targetPercentage
		}
	}

	tick()
	// 清除定时器以防止内存泄漏
	onUnmounted(() => {
		clearTimeout(timeoutId)
	})
}

async function fetchData() {
	percentage.value = 0
	try {
        await axios.get("/api/query", {
            onDownloadProgress: (progressEvent) => {
                const { loaded, total } = progressEvent;
                const percent = Math.round((loaded / total) * 100);
				percentage.value=percent
                console.log(`${percent}%`,progressEvent);
            },
        }).then((response) => {
            console.log(response.data);
        });
    } catch (error) {
        console.error("请求失败:", error);
        alert("获取数据时发生错误，请稍后再试。");
    }
	// const xhr = new XMLHttpRequest();
	//     xhr.open('GET', '/api/query');
	//     xhr.onreadystatechange = function () {
	//       if (xhr.readyState === 4 && xhr.status === 200) {
	//         const data = xhr.responseText;
	//       }
	//     }
	//     xhr.addEventListener('progress', e => {
	//       const { loaded, total } = e;

	//       console.log(parseInt((loaded / total) * 100, 0) + '%');
	//       percentage.value = parseInt((loaded / total) * 100, 0)
	//     })
	//     xhr.send()
}
</script>

<style lang="scss" scoped></style>
